import axios from 'axios'

const { uploadUrl } = useEnvUrl()
// 上传服务器
const uploadImage = formData => {
  return new Promise((resolve, reject) => {
    axios.post(uploadUrl, formData).then(res => {
      resolve(res.data.data)
    }).catch(err => {
      reject(err)
    })
  })
}

type ParamItem = {
  key: string
  val: any
}

// 粘贴事件
export const handlePaste = (event: ClipboardEvent, paramList: ParamItem[], uploadCallback: (res: any[]) => void, isDefault = true) => {
  // 阻止默认的粘贴行为
  if (isDefault) {
    event.preventDefault()
  }
  if (!event.clipboardData || !event.clipboardData.items) return

  const promiseList: Promise[] = []
  for (let i = 0; i < event.clipboardData.items.length; i++) {
    const item = event.clipboardData.items[i]
    // 检查是否为图片类型
    if (item.type.indexOf('image') === 0) {
      const blob = item.getAsFile()
      if (blob) {
        // 对每一个图片进行处理，例如上传到服务器
        const formData = new FormData()
        paramList.forEach((item: any) => {
          formData.append(item.key, item.val)
        })
        formData.append('file', blob)
        const promise = new Promise((resolve, reject) => {
          uploadImage(formData).then(res => {
            resolve(res)
          }).catch(err => {
            reject(err)
          })
        })
        promiseList.push(promise)
      }
    }
  }
  Promise.all(promiseList).then(res => {
    uploadCallback(res)
  })
}
